<template>
  <div class="relative">
    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
      <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
      </svg>
    </div>
    <input
      v-model="searchQuery"
      @input="handleSearch"
      @keyup.enter="onSearch"
      type="text"
      :placeholder="placeholder"
      class="input-field pl-10 pr-4"
      :disabled="disabled"
    />
    <div v-if="searchQuery" class="absolute inset-y-0 right-0 pr-3 flex items-center">
      <button
        @click="clearSearch"
        class="text-gray-400 hover:text-gray-600"
      >
        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
        </svg>
      </button>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { debounce } from '../utils'

export default {
  name: 'SearchBox',
  props: {
    placeholder: {
      type: String,
      default: '搜索...'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    debounceMs: {
      type: Number,
      default: 300
    }
  },
  emits: ['search', 'clear'],
  setup(props, { emit }) {
    const searchQuery = ref('')

    const handleSearch = debounce(() => {
      emit('search', searchQuery.value)
    }, props.debounceMs)

    const onSearch = () => {
      emit('search', searchQuery.value)
    }

    const clearSearch = () => {
      searchQuery.value = ''
      emit('clear')
    }

    return {
      searchQuery,
      handleSearch,
      onSearch,
      clearSearch
    }
  }
}
</script> 